// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  const bookmarkTitle = document.getElementById('title-input');
  const bookmarkUrl = document.getElementById('url-input');
  const bookmarkTags = document.getElementById('tags-input');
  const addButton = document.getElementById('add-button');
  const bookmarksContainer = document.getElementById('bookmarks-container');
  const tagButtonsContainer = document.getElementById('tag-buttons');
  const recentTagsButtons = document.getElementById('recent-tags-buttons');
  
  // 当前选中的标签
  let selectedTag = null;
  // 当前编辑的书签ID
  let editingBookmarkId = null;
  // 最近添加的标签
  let recentTags = [];
  
  // 初始化：加载书签和标签
  loadBookmarks();
  loadRecentTags();
  
  // 自动填充当前页面信息
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    if (tabs && tabs[0]) {
      bookmarkUrl.value = tabs[0].url;
      bookmarkTitle.value = tabs[0].title;
    }
  });
  
  // 添加书签按钮点击事件
  addButton.addEventListener('click', handleAddBookmark);
  
  // 处理添加书签
  function handleAddBookmark() {
    const title = bookmarkTitle.value.trim();
    const url = bookmarkUrl.value.trim();
    const tagsInput = bookmarkTags.value.trim();
    
    // 验证输入
    if (!title || !url) {
      alert('请输入标题和URL');
      return;
    }
    
    // 验证URL格式
    try {
      new URL(url);
    } catch (e) {
      alert('请输入有效的URL');
      return;
    }
    
    // 处理标签（支持逗号和空格作为分隔符）
    const tags = tagsInput ? tagsInput.split(/[,\s]+/).map(tag => tag.trim()).filter(tag => tag) : [];
    
    // 更新最近标签
    if (tags.length > 0) {
      updateRecentTags(tags);
    }
    
    // 获取现有书签
    chrome.storage.local.get('bookmarks', function(result) {
      const bookmarks = result.bookmarks || [];
      
      if (editingBookmarkId) {
        // 编辑现有书签
        const index = bookmarks.findIndex(b => b.id === editingBookmarkId);
        if (index !== -1) {
          bookmarks[index] = {
            ...bookmarks[index],
            title,
            url,
            tags,
            updatedAt: new Date().toISOString()
          };
        }
        editingBookmarkId = null;
        addButton.textContent = '添加书签';
      } else {
        // 添加新书签
        const newBookmark = {
          id: Date.now().toString(),
          title,
          url,
          tags,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        };
        bookmarks.unshift(newBookmark); // 添加到开头
      }
      
      // 保存书签
      chrome.storage.local.set({bookmarks}, function() {
        // 清空表单
        bookmarkTitle.value = '';
        bookmarkUrl.value = '';
        bookmarkTags.value = '';
        
        // 重新加载书签和标签
        loadBookmarks();
      });
    });
  }
  
  // 加载书签
  function loadBookmarks() {
    chrome.storage.local.get('bookmarks', function(result) {
      const bookmarks = result.bookmarks || [];
      
      // 过滤书签
      let filteredBookmarks = bookmarks;
      if (selectedTag) {
        filteredBookmarks = bookmarks.filter(bookmark => 
          bookmark.tags && bookmark.tags.includes(selectedTag)
        );
      }
      
      // 渲染书签列表
      renderBookmarks(filteredBookmarks);
      
      // 加载所有唯一标签
      loadTags(bookmarks);
    });
  }
  
  // 渲染最近标签
  function renderRecentTags() {
    recentTagsButtons.innerHTML = '';
    
    if (recentTags.length === 0) {
      recentTagsButtons.innerHTML = '<p class="no-recent-tags">暂无最近标签</p>';
      return;
    }
    
    recentTags.forEach(tag => {
      const button = document.createElement('button');
      button.className = 'recent-tag-btn';
      button.textContent = tag;
      button.addEventListener('click', () => {
        // 将标签添加到输入框中
        const currentTags = bookmarkTags.value.trim() ? 
          bookmarkTags.value.trim().split(/[,\s]+/).map(t => t.trim()).filter(t => t) : 
          [];
        
        if (!currentTags.includes(tag)) {
          currentTags.push(tag);
          bookmarkTags.value = currentTags.join(', ');
        }
      });
      recentTagsButtons.appendChild(button);
    });
  }
  
  // 更新最近标签
  function updateRecentTags(tags) {
    // 添加新标签到开头，并去重
    const updatedTags = [...new Set([...tags, ...recentTags])];
    // 只保留最近5个标签
    recentTags = updatedTags.slice(0, 5);
    
    // 保存到本地存储
    chrome.storage.local.set({ 'recentTags': recentTags }, function() {
      // 渲染更新后的最近标签
      renderRecentTags();
    });
  }
  
  // 加载最近标签
  function loadRecentTags() {
    chrome.storage.local.get('recentTags', function(result) {
      recentTags = result.recentTags || [];
      renderRecentTags();
    });
  }
  
  // 渲染书签列表
  function renderBookmarks(bookmarks) {
    bookmarksContainer.innerHTML = '';
    
    if (bookmarks.length === 0) {
      bookmarksContainer.innerHTML = `
        <div class="empty-state">
          <p>没有找到书签</p>
          <p>${selectedTag ? '尝试选择其他标签或添加新书签' : '点击上方按钮添加您的第一个书签吧'}</p>
        </div>
      `;
      return;
    }
    
    bookmarks.forEach(bookmark => {
      const bookmarkElement = document.createElement('div');
      bookmarkElement.className = 'bookmark-item';
      
      // 格式化标签
      const tagsHtml = bookmark.tags && bookmark.tags.length > 0 
        ? bookmark.tags.map(tag => `<span class="bookmark-tag">${tag}</span>`).join('')
        : '<span class="bookmark-tag">未分类</span>';
      
      bookmarkElement.innerHTML = `
        <div class="bookmark-title">${bookmark.title}</div>
        <a href="${bookmark.url}" target="_blank" class="bookmark-url">${truncateUrl(bookmark.url)}</a>
        <div class="bookmark-tags">
          ${tagsHtml}
        </div>
        <div class="bookmark-actions">
          <button class="edit-btn" data-id="${bookmark.id}">编辑</button>
          <button class="delete-btn" data-id="${bookmark.id}">删除</button>
        </div>
      `;
      
      bookmarksContainer.appendChild(bookmarkElement);
    });
    
    // 添加编辑和删除按钮的事件监听
    document.querySelectorAll('.edit-btn').forEach(btn => {
      btn.addEventListener('click', handleEditBookmark);
    });
    
    document.querySelectorAll('.delete-btn').forEach(btn => {
      btn.addEventListener('click', handleDeleteBookmark);
    });
  }
  
  // 加载标签
  function loadTags(bookmarks) {
    // 收集所有唯一标签
    const tagSet = new Set();
    bookmarks.forEach(bookmark => {
      if (bookmark.tags) {
        bookmark.tags.forEach(tag => tagSet.add(tag));
      }
    });
    
    const tags = Array.from(tagSet);
    
    // 渲染标签按钮
    tagButtonsContainer.innerHTML = '';
    
    // 添加"全部"按钮
    const allButton = document.createElement('button');
    allButton.className = `tag-btn ${selectedTag === null ? 'active' : ''}`;
    allButton.textContent = '全部';
    allButton.addEventListener('click', () => {
      selectedTag = null;
      loadBookmarks();
    });
    tagButtonsContainer.appendChild(allButton);
    
    // 添加标签按钮
    tags.forEach(tag => {
      const button = document.createElement('button');
      button.className = `tag-btn ${selectedTag === tag ? 'active' : ''}`;
      button.textContent = tag;
      button.addEventListener('click', () => {
        selectedTag = tag;
        loadBookmarks();
      });
      tagButtonsContainer.appendChild(button);
    });
  }
  
  // 处理编辑书签
  function handleEditBookmark(e) {
    const bookmarkId = e.target.dataset.id;
    
    chrome.storage.local.get('bookmarks', function(result) {
      const bookmarks = result.bookmarks || [];
      const bookmark = bookmarks.find(b => b.id === bookmarkId);
      
      if (bookmark) {
        // 填充表单
        bookmarkTitle.value = bookmark.title;
        bookmarkUrl.value = bookmark.url;
        bookmarkTags.value = bookmark.tags ? bookmark.tags.join(', ') : '';
        
        // 设置编辑模式
        editingBookmarkId = bookmarkId;
        addButton.textContent = '保存修改';
        
        // 滚动到表单
        document.querySelector('.add-bookmark').scrollIntoView({behavior: 'smooth'});
      }
    });
  }
  
  // 处理删除书签
  function handleDeleteBookmark(e) {
    const bookmarkId = e.target.dataset.id;
    
    if (confirm('确定要删除这个书签吗？')) {
      chrome.storage.local.get('bookmarks', function(result) {
        const bookmarks = result.bookmarks || [];
        const updatedBookmarks = bookmarks.filter(b => b.id !== bookmarkId);
        
        chrome.storage.local.set({bookmarks: updatedBookmarks}, function() {
          loadBookmarks();
        });
      });
    }
  }
  
  // 辅助函数：截断URL
  function truncateUrl(url) {
    // 移除协议和www
    let truncated = url.replace(/^https?:\/\/(www\.)?/, '');
    // 如果URL太长，截断显示
    if (truncated.length > 50) {
      truncated = truncated.substring(0, 50) + '...';
    }
    return truncated;
  }
});